﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

using AKMII.DMRA.Common;
using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Business.Service;
using AKMII.DMRA.Business.Rule;

namespace AKMII.DMRA.Web
{
    public partial class ManageMD : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["MDs"] = GetNewMartketDirectors();
                BindDataList();
            }
        }
       
        private void BindDataList()
        {
            int selectCount = 0;
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            newmds = (List<NewMartketDirector>)Session["MDs"];
            List<User> mds = new List<User>();
            foreach (NewMartketDirector nmd in newmds)
            {
                mds.Add(nmd.MD);
            }
            GridView1.DataSource = mds;
            GridView1.DataBind();
            for (int j = 0; j < newmds.Count; j++)
            {
                if (newmds[j].IsSelected)
                {
                    selectCount += 1;
                }
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chbItem = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                CheckBox chbActive = (CheckBox)GridView1.Rows[i].Cells[5].FindControl("chbActive");
                CheckBox chbIsPurchased = (CheckBox)GridView1.Rows[i].Cells[6].FindControl("chbIsPurchased");
                CheckBox chbRuleEnable = (CheckBox)GridView1.Rows[i].Cells[6].FindControl("chkRuleEnable");
                CheckBox chbRepeatRuleEnable = (CheckBox)GridView1.Rows[i].Cells[6].FindControl("chkRuleRepeatEnable");
                chbActive.Attributes.Add("onclick", "UserCheck(this);");
                chbIsPurchased.Attributes.Add("onclick", "ReOpenCheck(this);");
                chbRuleEnable.Attributes.Add("onclick", "RuleEnableCheck(this);");
                chbRepeatRuleEnable.Attributes.Add("onclick", "RuleRepetEnableCheck(this)");
                if (newmds[GridView1.PageSize * GridView1.PageIndex + i].MD.Status == UserStatus.Active)
                {
                    chbActive.Checked = true;
                }
                if (newmds[GridView1.PageSize * GridView1.PageIndex + i].IsPurchased == 1)
                {
                    chbIsPurchased.Checked = true;
                }
                if (newmds[GridView1.PageSize * GridView1.PageIndex + i].MD.IsRuleEnabled)
                {
                    chbRuleEnable.Checked = true;
                }
                if (newmds[GridView1.PageSize * GridView1.PageIndex + i].MD.IsRepeatRuleEnabled)
                {
                    chbRepeatRuleEnable.Checked = true;
                }
                chbItem.Checked = newmds[GridView1.PageSize * GridView1.PageIndex + i].IsSelected;
                switch (newmds[GridView1.PageSize * GridView1.PageIndex + i].OperatorType)
                { 
                    case OperatorStatus.Add:
                        GridView1.Rows[i].BackColor = Color.ForestGreen;
                        break;
                    case OperatorStatus.Edit:
                        GridView1.Rows[i].BackColor = Color.LightSkyBlue;
                        break;
                    case OperatorStatus.Delete:
                        GridView1.Rows[i].BackColor = Color.Red;
                        GridView1.Rows[i].Enabled = false;
                        break;
                    case OperatorStatus.Ignore:
                        GridView1.Rows[i].BackColor = Color.Orange;
                        GridView1.Rows[i].Enabled = false;
                        break;
                }
            }
            txtSelectedCount.Value = selectCount.ToString();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.EditIndex = -1;
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            newmds = (List<NewMartketDirector>)Session["MDs"];
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chbItem = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                CheckBox chbActive = (CheckBox)GridView1.Rows[i].Cells[5].FindControl("chbActive");
                CheckBox chbIsPurchased = (CheckBox)GridView1.Rows[i].Cells[6].FindControl("chbIsPurchased");
                CheckBox chbRuleEnable = (CheckBox)GridView1.Rows[i].Cells[6].FindControl("chkRuleEnable");
                CheckBox chbRepeatRuleEnable = (CheckBox)GridView1.Rows[i].Cells[6].FindControl("chkRuleRepeatEnable");
                if (newmds[GridView1.PageSize * GridView1.PageIndex + i].MD.IsRuleEnabled)
                {
                    chbRuleEnable.Checked = true;
                }
                if (newmds[GridView1.PageSize * GridView1.PageIndex + i].MD.IsRepeatRuleEnabled)
                {
                    chbRepeatRuleEnable.Checked = true;
                }
                if (chbActive.Checked)
                {
                    newmds[GridView1.PageSize * GridView1.PageIndex + i].MD.Status = UserStatus.Active;
                }
                if (chbIsPurchased.Checked)
                {
                    newmds[GridView1.PageSize * GridView1.PageIndex + i].IsPurchased = 1;
                }

                newmds[GridView1.PageSize * GridView1.PageIndex + i].IsSelected = chbItem.Checked;
            }
            Session["MDs"] = newmds;
            GridView1.PageIndex = e.NewPageIndex;
            BindDataList();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            GridView1.EditRowStyle.BackColor = Color.LightSkyBlue;
            BindDataList();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string firstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
            string lastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
            string email = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmail")).Text;
            bool active = ((CheckBox)GridView1.Rows[e.RowIndex].FindControl("chbActive")).Checked;
            bool IsPurchased = ((CheckBox)GridView1.Rows[e.RowIndex].FindControl("chbIsPurchased")).Checked;
            bool IsRuleEnable = ((CheckBox)GridView1.Rows[e.RowIndex].FindControl("chkRuleEnable")).Checked;
            bool IsRuleRepeatEnable = ((CheckBox)GridView1.Rows[e.RowIndex].FindControl("chkRuleRepeatEnable")).Checked;
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            newmds = (List<NewMartketDirector>)Session["MDs"];
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].OperatorType = OperatorStatus.Edit;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].MD.Email = email;
            //newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].IsSelected = true;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].MD.FirstName = firstName;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].MD.LastName = lastName;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].IsPurchased = (IsPurchased) ? 1 : 0;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].MD.IsRuleEnabled = IsRuleEnable;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].MD.IsRepeatRuleEnabled = IsRuleRepeatEnable;
            newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].MD.Status = active ? UserStatus.Active : UserStatus.Inactive;
            Response.Write(IsRuleEnable.ToString());
            GridView1.EditIndex = -1;
            Session["MDs"] = newmds;
            BindDataList();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            newmds = (List<NewMartketDirector>)Session["MDs"];
            for (int j = 0; j < newmds.Count; j++)
            {
                if (newmds[j].IsSelected)
                {
                    if (newmds[j].OperatorType == OperatorStatus.Add)
                    {
                        newmds[j].OperatorType = OperatorStatus.Ignore;
                    }
                    else
                    {
                        newmds[j].OperatorType = OperatorStatus.Delete;
                    }
                    newmds[j].IsSelected = true;
                }
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chbItem = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                if (chbItem.Checked)
                {
                    if (newmds[GridView1.PageSize * GridView1.PageIndex + i].OperatorType == OperatorStatus.Add)
                    {
                        newmds[GridView1.PageSize * GridView1.PageIndex + i].OperatorType = OperatorStatus.Ignore;
                    }
                    else
                    {
                        newmds[GridView1.PageSize * GridView1.PageIndex + i].OperatorType = OperatorStatus.Delete;
                    }
                    newmds[GridView1.PageSize * GridView1.PageIndex + i].IsSelected = true;
                }
            }

            Session["MDs"] = newmds;
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            newmds = (List<NewMartketDirector>)Session["MDs"];

            User user = new User();
            user.Email = txtAddEmail.Text;
            if (txtAddMDId.Text.Length > 4)
            {
                string id = txtAddMDId.Text;
                user.Id = id.Substring(id.Length - 4, 4);
            }
            else
            {
                user.Id = txtAddMDId.Text;
            }

            user.FirstName = txtAddFirstName.Text;
            user.DivisionNum = txtAddDivision.Text;
            user.LastName = txtAddLastName.Text;
            string password = Utility.BuildPassword(8);
            user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password,
                Constants.EncryptSetting);
            user.Type = UserType.MarketDirector;
            NewMartketDirector newmd = new NewMartketDirector();
            newmd.OperatorType = OperatorStatus.Add;
            newmd.MD = user;
            newmd.Password = password;
            newmds.Add(newmd);

            Session["MDs"] = newmds;
            GridView1.EditIndex = -1;
            BindDataList();

            txtAddEmail.Text = string.Empty;
            txtAddFirstName.Text = string.Empty;
            txtAddLastName.Text = string.Empty;
            txtAddMDId.Text = string.Empty;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            AccountManager am = new AccountManager();
            List<User> mds = am.GetUsers(UserType.MarketDirector);
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            for (int i = 0; i < mds.Count; i++)
            {
                NewMartketDirector nmd = new NewMartketDirector();
                nmd.MD = mds[i];
                newmds.Add(nmd);
            }
            Session["MDs"] = newmds;
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            newmds = (List<NewMartketDirector>)Session["MDs"];
            AccountManager am = new AccountManager();
            OrderManager om = new OrderManager();
            for (int i = 0; i < newmds.Count; i++)
            {
                switch (newmds[i].OperatorType)
                { 
                    case OperatorStatus.Add:
                        if (am.CreateUser(newmds[i].MD))
                        {
                            Mail mail = new Mail();
                            mail.Subject = "New Account Created";
                            mail.Content = "Your Id is " + newmds[i].MD.Id + " and your password is " + newmds[i].Password;
                            mail.Recipients = new List<string>() { newmds[i].MD.Email };

                            Thread thread = new Thread(new ParameterizedThreadStart(SendPassword));
                            thread.Start(mail);

                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), 
                                "isAdded", "<script type='text/javascript'>alert('Congratulations, you have added successfully! ');</script>");
                        }
                        else
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), 
                                "addfailed", "<script type='text/javascript'>alert('Sorry, you are failed! ');</script>");
                        }
                        break;
                    case OperatorStatus.Delete:
                        if(am.RemoveUserById(newmds[i].MD.Id))
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                                "isDelete", "<script type='text/javascript'>alert('Congratulations, you have deleted successfully! ');</script>");
                        }
                        else
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
                                "deletefailed", "<script type='text/javascript'>alert('Sorry, you have failed! ');</script>");
                        }
                        break;
                    case OperatorStatus.Edit:
                        if (am.UpdateUser(newmds[i].MD))
                        {
                            Order od = om.GetOrder(newmds[i].MD.Id, CurrentPeriod.Month, CurrentPeriod.Year);
                            if (od != null)
                            {
                                om.PurchaseOrder(od.Id, newmds[i].IsPurchased);
                            }

                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), 
                                "isEdited", "<script type='text/javascript'>alert('Congratulations, you have edited successfully! ');</script>");
                        }
                        else
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), 
                                "editfailed", "<script type='text/javascript'>alert('Sorry, you have failed! ');</script>");
                        }
                        break;
                    case OperatorStatus.Ignore:
                        break;
                }
            }
            newmds.Clear();

            Session["MDs"] = GetNewMartketDirectors();
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void SendPassword(object o)
        {
            Mail mail = o as Mail;
            if (mail != null)
            {
                CommonUtility.SendMail(mail);
            }
        }

        private List<NewMartketDirector> GetNewMartketDirectors()
        {
            AccountManager am = new AccountManager();
            List<User> mds = am.GetUsers(UserType.MarketDirector);
            List<NewMartketDirector> newmds = new List<NewMartketDirector>();
            OrderManager om = new OrderManager();
            for (int i = 0; i < mds.Count; i++)
            {
                NewMartketDirector nmd = new NewMartketDirector();
                nmd.MD = mds[i];
                Order od = om.GetOrder(nmd.MD.Id, CurrentPeriod.Month, CurrentPeriod.Year);

                nmd.IsPurchased = 0;
                if (od != null)
                {
                    nmd.IsPurchased = (od.IsPurchased == true) ? 1 : 0;
                }

                newmds.Add(nmd);
            }

            return newmds;
        }
    }
    
}
